package com.feiyuan.generator.service.impl;

import com.feiyuan.generator.mapper.DataSourceMapper;
import com.feiyuan.generator.pojo.entity.DataSourceEntity;
import com.feiyuan.generator.service.DataSourceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName DataSourceServiceImpl
 * @Description 数据源配置
 * @Author Xupf xupengfei131276@126.com
 * @Date 2021/9/30 9:45
 * @Version 1.0
 */
@Service
public class DataSourceServiceImpl extends ServiceImpl<DataSourceMapper, DataSourceEntity> implements DataSourceService {

    @Override
    public IPage<DataSourceEntity> listPage(Integer pageNo, Integer pageSize) {
        return this.baseMapper.selectPage(new Page<DataSourceEntity>(pageNo, pageSize),
                new QueryWrapper<DataSourceEntity>());
    }

    @Override
    public Object saveOrUpdateDataSource(DataSourceEntity dataSourceEntity) {
        if (dataSourceEntity.getIsDefault()) {
            this.updateIsDefault();
        }
        if (dataSourceEntity.getId() != null) {
            return this.baseMapper.updateById(dataSourceEntity);
        } else {
            return this.baseMapper.insert(dataSourceEntity);
        }
    }

    @Override
    public Boolean testDataSource(Long id) {
        DataSourceEntity dataSourceEntity = this.baseMapper.selectById(id);
        if (dataSourceEntity != null) {
            return this.getConnection(dataSourceEntity);
        }
        return null;
    }

    /**
     * 测试连接
     * @param dataSourceEntity
     * @return
     */
    private Boolean getConnection(DataSourceEntity dataSourceEntity) {
        Connection conn = null;
        try {
            Class.forName(dataSourceEntity.getClassName());
            conn = DriverManager.getConnection(dataSourceEntity.getUrl(), dataSourceEntity.getUserName(), dataSourceEntity.getPassword());
            if (conn != null) {
                return true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 修改默认值，列表中只能有一条数据是默认的
     */
    private void updateIsDefault() {
        List<DataSourceEntity> dataSourceEntities = this.baseMapper.selectList(new QueryWrapper<DataSourceEntity>().eq("is_default", true));
        if (dataSourceEntities != null && dataSourceEntities.size() > 0) {
            for (DataSourceEntity dataSourceEntity : dataSourceEntities) {
                dataSourceEntity.setIsDefault(false);
                this.baseMapper.updateById(dataSourceEntity);
            }
        }
    }
}
